package com.moter.one.wyydemo1.controller;

import com.moter.one.wyydemo1.backstage.vo.DataVo;
import com.moter.one.wyydemo1.entity.UserInfo;
import com.moter.one.wyydemo1.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
public class Register {
    @Autowired
    UserInfoService userInfoService;
    @CrossOrigin
    @RequestMapping("/Register")

    /**
     * 0是成功，1是失败
     */
    public DataVo<UserInfo> RegisterUser(@RequestBody UserInfo userInfo){
        List<UserInfo> list = userInfoService.searchAllUsers();//找到所有用户信息
        System.out.println(list);
        if(list == null) {//表示没有重复，注册成功
            int i = userInfoService.insertUserInfoMapper(userInfo);
            if(i>0){
                //插入成功
                //最后一个count 是无用的数据.
                DataVo<UserInfo> dataVo = new DataVo<UserInfo>(0,"插入成功",userInfo,123);
                return dataVo;
            }

            else {
                //插入失败
                DataVo<UserInfo> dataVo = new DataVo<UserInfo>(1,"插入失败",userInfo,123);
                return dataVo;
            }
        }
        else {
                if(Find(userInfo,list)){//注册成功
                    int i = userInfoService.insertUserInfoMapper(userInfo);
                    if(i>0){
                        //插入成功
                        DataVo<UserInfo> dataVo = new DataVo<UserInfo>(0,"插入成功",userInfo,123);
                        return dataVo;
                    }
                    else {
                        DataVo<UserInfo> dataVo = new DataVo<UserInfo>(1,"插入失败",userInfo,123);
                        return dataVo;
                    }//插入失败
                }
                else {
                    //表示注册失败由于主键重复了
                    DataVo<UserInfo> dataVo = new DataVo<UserInfo>(1,"插入失败",userInfo,123);
                    return dataVo;
                }
        }
    }
    public boolean Find(UserInfo userInfo,List<UserInfo> list){
           for(int i=0;i<list.size();i++){
               if(userInfo.getAccount().equals(list.get(i).getAccount()))return false;//表示主键重复了
           }
           return true;
    }
}
